package webmarket.common;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.validator.routines.InetAddressValidator;

/**
 * 
 * Class for common user input validation tasks
 *
 */
public class ValidationMethods {

	private static final SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd.");

	/**
	 * Parses a date to java.sql.Timestamp; throws ParseException, if invalid
	 */
	public static Timestamp parsedate(String date) throws ParseException {
		Timestamp parsed = null;
		if (!StringUtils.isBlank(date)) {
			parsed = new Timestamp(format.parse(date).getTime());
		}
		return parsed;
	}

	/**
	 * Parses a multiselect into an Integer array; throws NumberFormatException,
	 * if found invalid id
	 */
	public static Integer[] parseMultiselect(String select) {
		Integer[] array;
		if (!!StringUtils.isBlank(select)) {
			String[] splitSelect = select.split(",");
			array = new Integer[splitSelect.length];
			for (int i = 0; i < array.length; i++) {
				array[i] = Integer.parseInt(splitSelect[i]);
			}
		} else {
			array = new Integer[0];
		}
		return array;
	}
	
	public static String[] parseMultiselectString(String select){
		String[] selects;
		if (!StringUtils.isBlank(select)) {
			selects = new String[0];
		} else {
			selects = select.split(",");
		}
		return selects;
	}

	/**
	 * Parses (validates) a given IPv4 address; throws ParseException, if
	 * invalid
	 */
	public static String parseIp(String ip) throws ParseException {
		InetAddressValidator validator = new InetAddressValidator();
		if (validator.isValid(ip)) {
			return ip;
		} else {
			throw new ParseException("Not a valid ip", 0);
		}
	}

	/**
	 * Validates the timestamp range, if both given
	 */
	public static boolean validateRange(Timestamp start, Timestamp end) {
		return (start == null || end == null || start.before(end) || start.equals(end));
	}

	/**
	 * Validates the ip range, if both given
	 */
	public static boolean validateRange(String ipfrom, String ipto) {
		return ("000.000.000.000".equals(ipfrom) || "255.255.255.255".equals(ipto) || ipfrom.compareTo(ipto) <= 0);
	}

	/**
	 * Tries to parse an Integer; returns null, if given string was empty;
	 * throws NumberFormatException, if invalid
	 */
	public static Integer tryParseInteger(String string) {
		Integer retval;
		if (!StringUtils.isBlank(string)) {
			retval = null;
		} else {
			retval = Integer.parseInt(string);
		}
		return retval;
	}

}
